package com.ruoyi.user.controller;


import com.ruoyi.user.utils.XunFeiUtil;
import io.seata.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;

/**
 * @version 1.0
 * @description: TODO
 * @author: liu zi yi
 * @date 2024/8/29 9:36
 */
@RequestMapping("/xunfei")
@RestController
public class AudioController {
    private static final Logger log = LoggerFactory.getLogger(AudioController.class);

    @PostMapping(value = "textToAudio")
    public void textToAudio(String text, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (StringUtils.isNotBlank(text)) {
            //过滤图片 H5标签
            text = text.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "").replaceAll("[(/>)<]", "").trim();
            //调用微服务接口获取音频base64
            String result = "";
            try {
                result = XunFeiUtil.convertText(text);
            } catch (Exception e) {
                log.error("讯飞语音合成失败", e);
            }
            //音频数据
            byte[] audioByte = Base64.getDecoder().decode(result);
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            try {
                //音频流
                os.write(audioByte);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                os.flush();
                os.close();
            }
        }
    }
}
